/**
 * MIT License
 * Copyright (c) 2018 yadong.zhang
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.xuyiwei.xblog.core.util;

import org.apache.commons.codec.Charsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import javax.websocket.Session;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * websocket工具类，支持单条发送和批量发送
 *
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0
 * @website https://www.zhyd.me
 * @date 2018/4/18 11:48
 * @since 1.0
 */
public class WebSocketUtil {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketUtil.class);

    private static final String ONLINE_MSG_KEY = "online";
    private static final String NOTIFICATION_MSG_KEY = "notification";

    private WebSocketUtil() {
        // 私有化构造方法，禁止new
    }

    /**
     * 根据消息类型，生成发送到客户端的最终消息内容
     *
     * @param type
     *         消息类型
     * @param content
     *         消息正文
     * @return
     */
    private static String generateMsg(String type, String content) {
        return String.format("{\"fun\": \"%s\", \"msg\":\"%s\"}", type, content);
    }

    /**
     * 发送在线用户的消息
     *
     * @param msg
     * @param sessionMap
     */
    public static void sendOnlineMsg(String msg, ConcurrentHashMap<Long,Session> sessionMap,CopyOnWriteArraySet<Session> setSession) {
        broadOnlinecast(generateMsg(ONLINE_MSG_KEY, msg), sessionMap,setSession);
    }

    /**
     * 发送通知的消息
     *
     * @param msg
     * @param sessionMap
     */
    public static void sendNotificationMsg(String msg,ConcurrentHashMap<Long,Session> sessionMap,CopyOnWriteArraySet<Session> setSession) throws UnsupportedEncodingException {
        // 为了防止消息中存在特殊字符（比如换行符）等造成前台解析错误，此处编码一次。前台对应的需要解码
        broadOnlinecast(generateMsg(NOTIFICATION_MSG_KEY, URLEncoder.encode(msg, Charsets.UTF_8.displayName())), sessionMap,setSession);
    }

    /**
     * 向客户端发送消息
     *
     * @param message
     *        消息内容
     * @param userId
     *        发送信息名
     * @param sessionMap
     *        客户端session
     * @throws IOException
     */
    private static void sendMessage(String message, Long userId,ConcurrentHashMap<Long,Session> sessionMap) {
        try {
//            session.getAsyncRemote().sendText(message);
            if(sessionMap.get(userId)!=null){
                sessionMap.get(userId).getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            logger.error("websocket-->向客户端发送数据发生异常", e);
        }
    }

    /**
     * 向客户端发送消息
     *
     * @param message
     *         消息内容
     * @param session
     *         客户端session
     * @throws IOException
     */
    private static void sendMessage(String message, Session session) {
        try {
//            session.getAsyncRemote().sendText(message);
            session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            logger.error("websocket-->向客户端发送数据发生异常", e);
        }
    }

    /**
     * 群发
     *
     * @param message
     *         消息内容
     * @param sessionMap
     *         客户端session列表
     * @throws IOException
     */
    private static void broadOnlinecast(String message, ConcurrentHashMap<Long,Session> sessionMap,CopyOnWriteArraySet<Session> set) {
        if (CollectionUtils.isEmpty(sessionMap) && CollectionUtils.isEmpty(set) ) {
            return;
        }
        // 多线程群发
        for (Map.Entry<Long,Session> entry : sessionMap.entrySet()) {
            Session session = entry.getValue();
            if (null != session && session.isOpen()) {
                sendMessage(message, session);
            } else {
                sessionMap.remove(entry.getKey());
            }
        }

        // 多线程群发
        for (Session session: set ){
            if (null != session && session.isOpen()) {
                sendMessage(message, session);
            } else {
                set.remove(session);
            }
        }
    }
}
